package com.gaoda.booksystem.service.impl;


import com.gaoda.booksystem.entity.User;
import com.gaoda.booksystem.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CustomUserService implements UserDetailsService {
    @Autowired
    private UserMapper UserMapper;
    @Override
    public UserDetails loadUserByUsername(String username){
//        只要求用户查询出实际的用户信息。具体的密码验证工作，交由spring security完成
        User user=UserMapper.findUserByName(username);
        System.out.println("用户:"+user);
        if (user!=null) {
            System.out.println("用户:"+user);
            //授权，添加当前用户的角色
            List<GrantedAuthority> authorities = new ArrayList<>();
            //将权限信息添加到GrantedAuthority对象中
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(user.getUserType());
            authorities.add(grantedAuthority);
            return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),authorities);
        }else {
            throw new UsernameNotFoundException("admin:"+username+"do not exits!");
        }
    }
//    自定义用户登录实现层

}
